package cn.zl.ZLM.event.callback.impl;

import cn.zl.ZLM.core.ZLMApi;
import cn.zl.ZLM.event.callback.inter.IMKNoReaderCallBack;
import cn.zl.ZLM.helper.ZLMApiHelper;
import cn.zl.ZLM.structure.MK_MEDIA_SOURCE;
import cn.yunbamboos.Const;
import cn.zl.common.ZLConst;
import cn.zl.common.manage.StreamProxyManage;
import cn.zl.common.manage.VirtualVideoStreamManage;
import cn.yunbamboos.mybatis.conditions.Conditions;
import cn.zl.mapper.StreamProxyMapper;
import cn.zl.mapper.VirtualVideoStreamMapper;
import cn.zl.model.StreamProxy;
import cn.zl.model.VirtualVideoStream;
import com.sun.jna.CallbackThreadInitializer;
import com.sun.jna.Native;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class MKNoReaderCallBack implements IMKNoReaderCallBack {

    private static final Logger logger = LoggerFactory.getLogger(MKNoReaderCallBack.class);

    @Resource
    private VirtualVideoStreamMapper virtualVideoStreamMapper;
    @Resource
    private VirtualVideoStreamManage virtualVideoStreamManage;

    @Resource
    private StreamProxyMapper streamProxyMapper;
    @Resource
    private StreamProxyManage streamProxyManage;

    public MKNoReaderCallBack() {
        Native.setCallbackThreadInitializer(this, new CallbackThreadInitializer(true, false, "MediaNoReaderThread"));
    }

    @Override
    public void invoke(MK_MEDIA_SOURCE sender) {
        ZLMApi ZLM_API = ZLMApiHelper.getInstance().getApi();
        String schema = ZLM_API.mk_media_source_get_schema(sender);
        String app = ZLM_API.mk_media_source_get_app(sender);
        String stream = ZLM_API.mk_media_source_get_stream(sender);
        logger.info("[无人观看] schema:{} app:{}, stream:{} ", schema, app, stream);
        // 模拟视频流
        if (ZLConst.VIRTUAL_VIDEO.APP.equals(app)) {
            Optional<VirtualVideoStream> optional = virtualVideoStreamMapper.queryForObject(Conditions.create("app", app).add("stream", stream));
            optional.ifPresent(virtualVideoStream -> {
                virtualVideoStreamManage.stop(virtualVideoStream.getFileId());
            });
        }
        // 查询拉流代理
        Optional<StreamProxy> optional = streamProxyMapper.queryForObject(Conditions.create("app", app).add("stream", stream));
        if (optional.isPresent()) {
            StreamProxy streamProxy = optional.get();
            if (streamProxy.isAutoClose()) {
                streamProxyManage.stop(streamProxy.getProxyId());
            }
        }
    }
}
